package com.ssy.lingxi.purchase.handler.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * Jpa 将 Postgresql Json(或Jsonb)字段转换为Map<String, Object>
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/28
 */
@Converter(autoApply = true)
public class JpaStringToArrayConverter implements AttributeConverter<String[], String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将Map转换为数据库Json字段
     * @param meta
     * @return
     */
    @Override
    public String convertToDatabaseColumn(String[] meta) {
        try {
            return objectMapper.writeValueAsString(meta);
        } catch (JsonProcessingException ex) {
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库Json字段写入错误");
        }
    }

    /**
     * 将数据库Json字段转换为Map
     * @param dbData
     * @return
     */
    @Override
    public String[] convertToEntityAttribute(String dbData) {
        try {
            return objectMapper.readValue(dbData, new TypeReference<String[]>() {});
        } catch (JsonProcessingException ex) {
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库Json字段反序列化错误");
        }
    }
}
